package org.ix.net.controllers;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.ix.net.BaseMuteServlet;

public class Downloader extends BaseMuteServlet {

    // eg. http://localhost:8080/app/download?localfilename=test.pdf&filename=C:\\Progetti\\bin\\bshmanual.pdf
    protected void serve(HttpServletRequest req, HttpServletResponse res) {
        String filename = req.getParameter("filename");
        String localFileName = req.getParameter("localfilename");
        
        File file = new File(filename);
        int length = 0;
        try {
            ServletOutputStream outStream = res.getOutputStream();
            ServletContext context = getServletConfig().getServletContext();
            String mimetype = context.getMimeType(filename);

            res.setContentType((mimetype != null) ? mimetype : "application/octet-stream");
            res.setContentLength((int) file.length());
            res.setHeader("Content-Disposition", "attachment; filename=\"" + localFileName + "\"");

            byte[] buffer = new byte[1024];
            DataInputStream inputStream = new DataInputStream(new FileInputStream(file));

            if (inputStream == null) {
                return;
            }

            while ((length = inputStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, length);
            }

            inputStream.close();
            outStream.flush();
            outStream.close();
        } catch (Exception genexc) {
            //out.print("Errore in scaricamento file: " + genexc.getMessage());
            genexc.printStackTrace();
        }
    }

    public String getServletInfo() {
        return "Share servlet";
    }
}
